import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { prisma } from '@/lib/prisma';
import { authenticateRequest } from '@/utils/auth';
import type { ChatSession, CreateChatSessionRequest } from '@/types/chat';

// POST /api/client/chat/sessions/create - 创建新的聊天会话
async function handlePost(request: NextRequest): Promise<ChatSession> {
  // 1. 权限验证
  const authResult = await authenticateRequest(request);
  if (!authResult.success) {
    throw new Error(authResult.error || '认证失败');
  }

  // 2. 获取当前用户ID
  const userId = authResult.user?.id;
  if (!userId) {
    throw new Error('用户信息不存在');
  }

  // 3. 解析参数
  const body: CreateChatSessionRequest = await request.json();
  const { title, agentId } = body;

  // 4. 生成新的 chatId
  const chatId = `chat_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;

  // 5. 创建新的聊天会话
  const chatSession = await prisma.chatSession.create({
    data: {
      chatId,
      title: title || '新对话',
      userId: userId,
      agentId: agentId
    }
  });

  // 6. 数据转换
  return {
    id: chatSession.id,
    chatId: chatSession.chatId,
    title: chatSession.title || '新对话',
    userId: chatSession.userId,
    createdAt: chatSession.createdAt.toISOString(),
    updatedAt: chatSession.updatedAt.toISOString(),
    messageCount: 0
  };
}

export const POST = withMiddleware(handlePost);
